from datetime import datetime
from time import localtime, strftime
from os.path import dirname, realpath, exists, isdir
from os import environ, system
from subprocess import Popen, PIPE

from PyQt5.QtGui import QIcon
from PIL import Image
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager as Manager


__path = f'{dirname(realpath(__file__))}/..'
__option = Options()


__option.add_argument('--headless')
__option.add_argument('--disable-extensions')


def drive():
    """ Creating object of chromedriver. """
    return Chrome(service=Service(Manager().install()), options=__option)


def countPercent(index, length): return int((index + 1) / length * 100)


def seticon(icon=None):
    """ Creating object of QIcon """
    return QIcon() if icon is None else QIcon(f'{__path}/icons/{icon}.png')


def setimg(img): return QIcon(img)


def numType(val): return float(val) if '.' in str(val) else int(val)


def singleNotify(data, name): return [i for i in data if name not in i]


def notifySend(data, current, new, name, mode="M"):
    """ Generating notification by condition. """
    if current != new and new:
        data = singleNotify(data, name)
        date = datetime.now().strftime('%d/%m/%Y - ')
        c_t = strftime("%H:%M", localtime())
        body = f'[{mode}][{date}{c_t}] > {name} - new chapter {new}'
        log = f'{name} → {new}'
        return body, log, data
    return None, None, data


def loadImage(name):
    """ Resizing an image. """
    width, height, path = 90, 110, f'{environ["HOME"]}/.cache/anima'
    if exists(f'{path}/description/raw/{name}'):
        img = Image.open(f'{path}/description/raw/{name}')
        resizing = img.resize((width, height), Image.ANTIALIAS)
        resizing.save(f'{path}/description/small/{name}')
        return f'description/small/{name}'
    return None


def checkVoice(notify, tray, check, mode):
    """ Show message new release series or chapters. """
    if check is not None and mode is not None and check > 0:
        notify, head = 'unchecked', 'Updating:'
        txt = ('released new series of anime',
               'released new chapters of manga',
               'released new chapters of ranobe')
        new = ("\n".join(txt[:2]), "\n".join((txt[0], txt[2])),
               "\n".join(txt[1:]), '\n'.join(txt))
        tray.showMessage(head, (txt+new)[mode], seticon('notify'), msecs=10000)
    return notify


def checkPathResources():
    path = f'{environ["HOME"]}/.cache/anima/description/'
    [system(f'mkdir -pv "{path}{i}"') for i in ('raw', 'small')
                                                    if not isdir(f"{path}{i}")]


def networkConnected():
    query = 'wget -q --spider http://google.com'
    head = 'if [ $? -eq 0 ]; then echo "1"; else echo "0"; fi'
    return 1 if Popen(f'{query} && {head}', stdout=PIPE,
                 shell=True).communicate()[0].decode().split('\n')[0] else 0
